<template>
  <div class="home flex flex-col justify-center items-center bg-gray-500">
    <div class="file-upload-container bg-white p-8 rounded-lg shadow-lg max-w-md w-full">
      <h1 class="text-2xl font-bold mb-6 text-center">文件上传并转换为ArrayBuffer</h1>
      
      <!-- 隐藏的文件输入 -->
      <input 
        ref="fileInput" 
        type="file" 
        class="hidden"
        @change="handleFileChange"
      />
      
      <!-- 上传按钮 -->
      <button 
        @click="triggerFileUpload"
        class="w-full py-3 px-4 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-md transition-colors duration-200 flex justify-center items-center gap-2"
      >
        <span>选择文件</span>
      </button>
      
      <!-- 显示已选文件信息 -->
      <div v-if="selectedFile" class="mt-4 p-3 bg-gray-100 rounded-md">
        <p class="text-sm text-gray-700"><strong>文件名：</strong>{{ selectedFile.name }}</p>
        <p class="text-sm text-gray-700"><strong>大小：</strong>{{ formatFileSize(selectedFile.size) }}</p>
        <p class="text-sm text-gray-700"><strong>类型：</strong>{{ selectedFile.type }}</p>
      </div>
      
      <!-- 显示处理状态 -->
      <div v-if="processing" class="mt-4 text-center">
        <p class="text-blue-600">正在处理文件...</p>
      </div>
      
      <!-- 显示转换结果 -->
      <div v-if="arrayBufferResult" class="mt-4">
        <h3 class="text-lg font-semibold mb-2">转换结果</h3>
        <p class="text-sm text-gray-700"><strong>ArrayBuffer 长度：</strong>{{ arrayBufferResult.byteLength }} bytes</p>
        <button 
          @click="clearResults"
          class="mt-2 text-sm py-1 px-3 bg-gray-200 hover:bg-gray-300 rounded-md transition-colors"
        >
          清除结果
        </button>
      </div>
      
      <!-- 错误消息 -->
      <div v-if="error" class="mt-4 p-3 bg-red-100 text-red-700 rounded-md">
        {{ error }}
      </div>
    </div>
    <div class="canvas-editor" ref="canvasEditorRef"></div>
  </div>
</template>

<script setup>
import Editor from '@hufe921/canvas-editor'
import docxPlugin from '@hufe921/canvas-editor-plugin-docx'
import { ref, onMounted } from 'vue'

// 响应式数据
const canvasEditorRef = ref(null)
let canvasEditorInstance = null




// 响应式数据
const fileInput = ref(null)
const selectedFile = ref(null)
const arrayBufferResult = ref(null)
const processing = ref(false)
const error = ref(null)

// 触发文件选择对话框
const triggerFileUpload = () => {
  fileInput.value?.click()
}

// 处理文件选择变化
const handleFileChange = (event) => {
  const file = event.target.files?.[0]
  if (file) {
    selectedFile.value = file
    processFileToBuffer(file)
  }
}

// 将文件转换为ArrayBuffer
const processFileToBuffer = (file) => {
  processing.value = true
  error.value = null
  arrayBufferResult.value = null
  
  const reader = new FileReader()
  
  reader.onload = (e) => {
    try {
      // 获取ArrayBuffer
      const buffer = e.target.result
      arrayBufferResult.value = buffer
      if(canvasEditorInstance){
        canvasEditorInstance.command.executeImportDocx({
          arrayBuffer:buffer
        })
      }
      console.log('文件转换为ArrayBuffer成功:', buffer)
    } catch (err) {
      error.value = '转换文件时出错: ' + err.message
      console.error('文件转换错误:', err)
    } finally {
      processing.value = false
    }
  }
  
  reader.onerror = () => {
    error.value = '读取文件时出错'
    processing.value = false
    console.error('文件读取错误')
  }
  
  // 开始读取文件为ArrayBuffer
  reader.readAsArrayBuffer(file)
}

// 格式化文件大小显示
const formatFileSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB'
  else return (bytes / 1048576).toFixed(2) + ' MB'
}

// 清除结果
const clearResults = () => {
  selectedFile.value = null
  arrayBufferResult.value = null
  error.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const initEditor = ()=>{
  const instance = new Editor(canvasEditorRef.value,{
    main: [
      {
        value: 'Hello World'
      }
    ]
  })
  // instance.use(docxPlugin)
  canvasEditorInstance = instance
}
// 初始化编辑器
onMounted(() => {
  if(canvasEditorRef.value){
    initEditor()
  }
})
</script>

<style scoped>
.home {
  min-height: 100vh;
  padding: 2rem;
}

.file-upload-container {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>